﻿Imports System.IO
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.Data
Imports ExcelDataReader
Imports ExcelDataReader.Exceptions
Imports System.ComponentModel
Imports System.Reflection
Imports Sunny.UI
Imports System.Text

Public Class Form2
    Private isPasting As Boolean = False
    Private dataTable As DataTable
    Private jsonFilePath As String = ""

    Private 当前教材Path As String
    Private 当前教材Name As String

    Private dragRowIndex As Integer = -1
    Private dragCursorRect As Rectangle

    ' 定义JSON数据结构
    Public Class Library
        <JsonProperty("library_name")>
        Public Property LibraryName As String
        <JsonProperty("other")>
        Public Property Other As String
        <JsonProperty("units")>
        Public Property Units As List(Of Unit)
    End Class
    Public Class Unit
        <JsonProperty("unit_name")>
        Public Property UnitName As String
        <JsonProperty("theme")>
        Public Property Theme As String
        <JsonProperty("words")>
        Public Property Words As List(Of Word)
    End Class

    Public Class Word
        <JsonProperty("word")>
        Public Property Word As String
        ' 其他字段根据需要添加

        <JsonProperty("phonetic")>
        Public Property Phonetic As String

        <JsonProperty("translation")>
        Public Property Translation As String

        <JsonProperty("en_example")>
        Public Property en_Example As String

        <JsonProperty("cn_example")>
        Public Property cn_Example As String
        <JsonProperty("annotation")>
        Public Property Annotation As String
        <JsonProperty("other")>
        Public Property Other As String
    End Class

    Public Class QuestionBank
        <JsonProperty("Bank_Name")>
        Public Property BankName As String
        <JsonProperty("Other")>
        Public Property Other As String
        <JsonProperty("Questions")>
        Public Property QuestionItems As List(Of QuestionItem)
    End Class
    Public Class QuestionItem
        <JsonProperty("Index")>
        Public Property index As String
        <JsonProperty("Question")>
        Public Property question As String
        <JsonProperty("Answer")>
        Public Property answer As String
    End Class
    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.DoubleBuffered = True
        Dim type As Type = UiDataGridView1.GetType()
        Dim pi As PropertyInfo = type.GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.NonPublic)
        pi.SetValue(UiDataGridView1, True, Nothing)
        ToolStripSplitButton2.Enabled = False
        ScanDictBookFolders()
    End Sub
    Private Sub ScanDictBookFolders()
        Dim dictBookPath = Path.Combine(Application.StartupPath, "DictBook")

        If Not Directory.Exists(dictBookPath) Then
            MessageBox.Show($"DictBook文件夹不存在: {dictBookPath}")
            Return
        End If

        ' 获取一级文件夹
        Dim topLevelDirs = Directory.GetDirectories(dictBookPath)

        For Each topDir In topLevelDirs
            Dim topDirName = Path.GetFileName(topDir)

            ' 获取二级文件夹
            Dim subDirs = Directory.GetDirectories(topDir)

            If subDirs.Length = 0 Then
                ' 没有子文件夹，添加一级菜单项
                AddFolderMenuItem(topDirName, topDir)
            Else
                ' 添加所有子文件夹菜单项
                For Each subDir In subDirs
                    Dim subDirName = Path.GetFileName(subDir)
                    AddFolderMenuItem($"{topDirName}-{subDirName}", subDir)
                Next
            End If
        Next
    End Sub

    Private Sub AddFolderMenuItem(text As String, folderPath As String)
        Dim menuItem = New ToolStripMenuItem(text)
        menuItem.Tag = folderPath
        AddHandler menuItem.Click, AddressOf FolderMenuItem_Click
        ToolStripSplitButton1.DropDownItems.Add(menuItem)
    End Sub

    Private Sub FolderMenuItem_Click(sender As Object, e As EventArgs)
        Dim menuItem = DirectCast(sender, ToolStripMenuItem)
        Dim folderPath = menuItem.Tag.ToString()
        ToolStripSplitButton1.Text = menuItem.Text
        ' 清除之前的词库列表
        ToolStripSplitButton2.DropDownItems.Clear()

        ' 扫描文件夹中的JSON文件
        ScanJsonFilesInFolder(folderPath)
        If ToolStripSplitButton2.DropDownItems.Count > 0 Then ToolStripSplitButton2.Enabled = True
    End Sub

    Private Sub ScanJsonFilesInFolder(folderPath As String)
        Dim jsonFiles = Directory.GetFiles(folderPath, "*.json")

        If jsonFiles.Length = 0 Then
            MessageBox.Show($"文件夹中没有找到JSON文件: {folderPath}")
            Return
        End If

        For Each jsonFile In jsonFiles
            Try
                ' 读取JSON文件获取library_name
                Dim json = File.ReadAllText(jsonFile)
                Dim root = JObject.Parse(json)
                Dim libraryName = root("library_name").ToString()

                ' 添加词库菜单项
                Dim menuItem = New ToolStripMenuItem(libraryName)
                menuItem.Tag = jsonFile
                AddHandler menuItem.Click, AddressOf LibraryMenuItem_Click
                ToolStripSplitButton2.DropDownItems.Add(menuItem)
            Catch ex As Exception
                MessageBox.Show($"读取JSON文件失败: {Path.GetFileName(jsonFile)} - {ex.Message}")
            End Try
        Next
    End Sub

    Private Sub LibraryMenuItem_Click(sender As Object, e As EventArgs)
        Dim menuItem = DirectCast(sender, ToolStripMenuItem)
        Dim jsonFile = menuItem.Tag.ToString()
        ToolStripSplitButton2.Text = menuItem.Text
        ' 加载JSON文件到DataGridView
        LoadJsonToDataGridView(jsonFile)
    End Sub

    Private Sub GetUnitsWordsCount()
        '统计单元数量
        If dataTable Is Nothing OrElse dataTable.Rows.Count = 0 Then
            Label3.Text = "单元数：0"
            Label4.Text = "单词数：0"
        Else
            ' 使用LINQ查询不同的单元名称
            Dim distinctUnits = From row As DataRow In dataTable.Rows
                                Let unitName = row("单元名称").ToString()
                                Where Not String.IsNullOrWhiteSpace(unitName)
                                Select unitName
                                Distinct

            Label3.Text = "单元数：" & distinctUnits.Count()
            Label4.Text = "单词数：" & dataTable.Rows.Count - 1
        End If
    End Sub

    Private Sub ToolStripButton6_Click(sender As Object, e As EventArgs) Handles ToolStripButton6.Click
        If dataTable Is Nothing OrElse dataTable.Rows.Count = 0 Then
            ShowWarningTip("没有数据可导出！")
            Return
        End If

        ' 创建根JSON对象
        Dim root = New JObject()
        root("library_name") = TextBox1.Text
        root("other") = TextBox2.Text

        Dim unitsArray As New JArray()

        ' 分组处理单元数据
        Dim currentUnit As String = Nothing
        Dim currentTheme As String = Nothing
        Dim unitWords As New List(Of JObject)()

        OrganizeDataBeforeSave()

        For Each row As DataRow In dataTable.Rows
            Dim unitName = If(row("单元名称") IsNot DBNull.Value, row("单元名称").ToString(), "")
            Dim theme = If(row("单元主题") IsNot DBNull.Value, row("单元主题").ToString(), "")

            ' 当检测到新单元时，保存当前单元
            If unitName <> currentUnit AndAlso currentUnit IsNot Nothing Then
                Dim unitObj As New JObject()
                unitObj("unit_name") = currentUnit
                unitObj("theme") = currentTheme
                unitObj("words") = JArray.FromObject(unitWords)
                unitsArray.Add(unitObj)
                unitWords = New List(Of JObject)()
            End If

            ' 更新当前单元信息
            currentUnit = unitName
            currentTheme = theme

            ' 添加单词数据
            Dim wordObj As New JObject()
            wordObj("word") = If(row("单词") IsNot DBNull.Value, row("单词").ToString(), "")
            wordObj("phonetic") = If(row("音标") IsNot DBNull.Value, row("音标").ToString(), "")
            wordObj("translation") = If(row("词意") IsNot DBNull.Value, row("词意").ToString(), "")
            wordObj("en_example") = If(row("英文例句") IsNot DBNull.Value, row("英文例句").ToString(), "")
            wordObj("cn_example") = If(row("中文例句") IsNot DBNull.Value, row("中文例句").ToString(), "")
            wordObj("annotation") = If(row("注释") IsNot DBNull.Value, row("注释").ToString(), "")
            wordObj("other") = If(row("其它") IsNot DBNull.Value, row("其它").ToString(), "")

            unitWords.Add(wordObj)
        Next

        ' 添加最后一个单元
        If currentUnit IsNot Nothing Then
            Dim unitObj As New JObject()
            unitObj("unit_name") = currentUnit
            unitObj("theme") = currentTheme
            unitObj("words") = JArray.FromObject(unitWords)
            unitsArray.Add(unitObj)
        End If

        root("units") = unitsArray

        ' 保存JSON文件
        Using saveDialog As New SaveFileDialog
            saveDialog.Filter = "JSON文件|*.json"
            saveDialog.InitialDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DictBook")
            If saveDialog.ShowDialog() = DialogResult.OK Then
                File.WriteAllText(saveDialog.FileName, root.ToString(Formatting.Indented))
                ShowSuccessTip("另存成功！")
            End If
        End Using

    End Sub

    Private Sub ToolStripButton7_Click(sender As Object, e As EventArgs) Handles ToolStripButton7.Click
        '    Dim keyword = ToolStripTextBox1.Text.Trim()
        '    If String.IsNullOrEmpty(keyword) Then
        '        'LoadToDataGridView(originalQuestionBank)
        '        Return
        '    End If

        '    ' 创建筛选后的题库 - 基于原始题库而不是当前题库
        '    Dim filteredBank As New QuestionBank() With {
        '.BankName = originalQuestionBank.BankName & "(筛选)",
        '.Other = $"关键词: {keyword}",
        '.QuestionItems = originalQuestionBank.QuestionItems.
        '                 Where(Function(q) q.question.Contains(keyword) OrElse
        '                                  q.answer.Contains(keyword)).
        '                 ToList()
        '}

        ' 加载筛选结果
        'LoadToDataGridView(filteredBank, True) ' 添加True参数表示这是筛选结果
    End Sub

    Private Sub ToolStripButton8_Click(sender As Object, e As EventArgs) Handles ToolStripButton8.Click
        'ToolStripTextBox1.Text = ""
        'If originalQuestionBank IsNot Nothing Then
        '    'LoadToDataGridView(originalQuestionBank)
        'End If
    End Sub

    Private Sub ToolStripButton9_Click(sender As Object, e As EventArgs) Handles ToolStripButton9.Click
        SaveData()
    End Sub
    Private Sub SaveData()

        If dataTable Is Nothing OrElse dataTable.Rows.Count = 0 Then
            ShowWarningTip("没有数据！")
            Return
        End If

        ' 创建根JSON对象
        Dim root = New JObject()
        root("library_name") = TextBox1.Text
        root("other") = TextBox2.Text

        Dim unitsArray As New JArray()

        ' 分组处理单元数据
        Dim currentUnit As String = Nothing
        Dim currentTheme As String = Nothing
        Dim unitWords As New List(Of JObject)()

        OrganizeDataBeforeSave()

        For Each row As DataRow In dataTable.Rows
            Dim unitName = If(row("单元名称") IsNot DBNull.Value, row("单元名称").ToString(), "")
            Dim theme = If(row("单元主题") IsNot DBNull.Value, row("单元主题").ToString(), "")

            ' 当检测到新单元时，保存当前单元
            If unitName <> currentUnit AndAlso currentUnit IsNot Nothing Then
                Dim unitObj As New JObject()
                unitObj("unit_name") = currentUnit
                unitObj("theme") = currentTheme
                unitObj("words") = JArray.FromObject(unitWords)
                unitsArray.Add(unitObj)
                unitWords = New List(Of JObject)()
            End If

            ' 更新当前单元信息
            currentUnit = unitName
            currentTheme = theme

            ' 添加单词数据
            Dim wordObj As New JObject()
            wordObj("word") = If(row("单词") IsNot DBNull.Value, row("单词").ToString(), "")
            wordObj("phonetic") = If(row("音标") IsNot DBNull.Value, row("音标").ToString(), "")
            wordObj("translation") = If(row("词意") IsNot DBNull.Value, row("词意").ToString(), "")
            wordObj("en_example") = If(row("英文例句") IsNot DBNull.Value, row("英文例句").ToString(), "")
            wordObj("cn_example") = If(row("中文例句") IsNot DBNull.Value, row("中文例句").ToString(), "")
            wordObj("annotation") = If(row("注释") IsNot DBNull.Value, row("注释").ToString(), "")
            wordObj("other") = If(row("其它") IsNot DBNull.Value, row("其它").ToString(), "")

            unitWords.Add(wordObj)
        Next

        ' 添加最后一个单元
        If currentUnit IsNot Nothing Then
            Dim unitObj As New JObject()
            unitObj("unit_name") = currentUnit
            unitObj("theme") = currentTheme
            unitObj("words") = JArray.FromObject(unitWords)
            unitsArray.Add(unitObj)
        End If

        root("units") = unitsArray

        ' 保存JSON文件

        If String.IsNullOrEmpty(当前教材Path) Then
            ' 如果没有路径，弹出另存为对话框
            Using saveDialog As New SaveFileDialog()
                saveDialog.Filter = "JSON文件|*.json"
                saveDialog.Title = "保存题库文件"
                saveDialog.InitialDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DictBook")

                If saveDialog.ShowDialog() = DialogResult.OK Then
                    当前教材Path = saveDialog.FileName
                Else
                    Return ' 用户取消保存
                End If
            End Using
        End If
        File.WriteAllText(当前教材Path, root.ToString(Formatting.Indented))
        ShowSuccessTip("保存成功！")

    End Sub

    ' 添加新行的方法
    Private Sub AddNewRow()

        If dataTable Is Nothing Then
            ' 如果还没有数据表，创建一个新的
            dataTable = New DataTable()
            dataTable.Columns.Add("单元名称")
            dataTable.Columns.Add("单元主题")
            dataTable.Columns.Add("单词")
            dataTable.Columns.Add("音标")
            dataTable.Columns.Add("词意")
            dataTable.Columns.Add("英文例句")
            dataTable.Columns.Add("中文例句")
            dataTable.Columns.Add("注释")
            dataTable.Columns.Add("其它")

            UiDataGridView1.DataSource = dataTable
        End If

        Dim insertIndex As Integer
        If UiDataGridView1.CurrentCell IsNot Nothing Then
            Dim selectedIndex = UiDataGridView1.CurrentCell.RowIndex
            insertIndex = selectedIndex + 1
        Else
            ' 没有选中行，添加到末尾
            insertIndex = dataTable.Rows.Count
        End If

        ' 添加新行
        Dim newRow = dataTable.NewRow()
        dataTable.Rows.InsertAt(newRow, insertIndex)
        GetUnitsWordsCount()
    End Sub
    Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Handles ToolStripButton3.Click
        ' 强制结束所有编辑
        UiDataGridView1.EndEdit()
        ' 检查是否有选中行
        Dim hasSelected As Boolean = False
        For Each row As DataGridViewRow In UiDataGridView1.Rows
            If row.Cells("CheckboxColumn").Value = True Then
                hasSelected = True
                Exit For
            End If
        Next

        If Not hasSelected Then
            MessageBox.Show("请先选择要删除的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return
        End If

        ' 确认删除
        If MessageBox.Show("确定要删除选中的题目吗？", "确认删除",
                          MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
            Return
        End If

        ' 获取数据源
        Dim dataSource = TryCast(UiDataGridView1.DataSource, BindingList(Of QuestionItem))

        ' 创建要删除的索引列表
        Dim indexesToDelete As New List(Of Integer)()

        ' 收集要删除的行索引
        For i As Integer = 0 To UiDataGridView1.Rows.Count - 1
            Dim row As DataGridViewRow = UiDataGridView1.Rows(i)
            If CBool(row.Cells("CheckboxColumn").Value) Then
                indexesToDelete.Add(i)
            End If
        Next

        ' 按降序排序索引（从大到小）
        indexesToDelete.Sort()
        indexesToDelete.Reverse()

        ' 删除行
        For Each index As Integer In indexesToDelete
            If dataSource IsNot Nothing Then
                ' 从绑定数据源删除
                dataSource.RemoveAt(index)
            Else
                ' 直接删除行
                UiDataGridView1.Rows.RemoveAt(index)
            End If
        Next
        GetUnitsWordsCount()
        ShowSuccessTip("已删除选中的题目！")

    End Sub


    Private Sub ToolStripButton4_Click(sender As Object, e As EventArgs) Handles ToolStripButton4.Click
        AddNewRow()
    End Sub
    ' 添加复选框列
    Private Sub AddCheckboxColumn()
        ' 检查是否已存在复选框列
        If UiDataGridView1.Columns.Contains("CheckboxColumn") Then
            Return
        End If

        ' 创建复选框列
        Dim checkboxColumn As New DataGridViewCheckBoxColumn()
        checkboxColumn.Name = "CheckboxColumn"
        checkboxColumn.HeaderText = "选择"
        checkboxColumn.Width = 50
        checkboxColumn.FlatStyle = FlatStyle.Standard
        checkboxColumn.TrueValue = True
        checkboxColumn.FalseValue = False

        ' 添加到第一列位置
        UiDataGridView1.Columns.Insert(0, checkboxColumn)

    End Sub

    Private Sub LoadJsonToDataGridView(filePath As String)
        Try
            Dim json = File.ReadAllText(filePath)
            Dim root = JObject.Parse(json)
            TextBox1.Text = root("library_name").ToString
            TextBox2.Text = root("other").ToString
            Label3.Text = "单元数：" & root("units").Count.ToString
            ' 创建新的DataTable
            Dim dt = New DataTable()
            dt.Columns.Add("单元名称")
            dt.Columns.Add("单元主题")
            dt.Columns.Add("单词")
            dt.Columns.Add("音标")
            dt.Columns.Add("词意")
            dt.Columns.Add("英文例句")
            dt.Columns.Add("中文例句")
            dt.Columns.Add("注释")
            dt.Columns.Add("其它")

            ' 遍历所有单元和单词
            For Each unit In root("units")
                Dim unitName = unit("unit_name").ToString()
                Dim theme = unit("theme").ToString()

                For Each word In unit("words")
                    Dim row = dt.NewRow()
                    row("单元名称") = unitName
                    row("单元主题") = theme
                    row("单词") = word("word").ToString()
                    row("音标") = word("phonetic").ToString()
                    row("词意") = word("translation").ToString()
                    row("英文例句") = word("en_example").ToString()
                    row("中文例句") = word("cn_example").ToString()
                    row("注释") = word("annotation").ToString()
                    row("其它") = word("other").ToString()

                    dt.Rows.Add(row)
                Next
            Next

            dataTable = dt
            UiDataGridView1.DataSource = dataTable
            GetUnitsWordsCount()
            当前教材Path = filePath
            AddCheckboxColumn()
            ShowSuccessTip("教材加载成功！")
        Catch ex As Exception
            ShowErrorTip($"加载JSON失败: {ex.Message}")

        End Try
    End Sub

    Private Sub ToolStripButton10_Click(sender As Object, e As EventArgs) Handles ToolStripButton10.Click
        ' 确认操作
        If MessageBox.Show("确定要清空所有单词吗？此操作不可撤销！",
                          "确认清空",
                          MessageBoxButtons.YesNo,
                          MessageBoxIcon.Warning) = DialogResult.No Then
            Return
        End If

        dataTable.Clear()

        ' 重置原始题库引用（如果需要）
        ShowSuccessTip("所有单词已清空！")
    End Sub

    Private Sub ToolStripSplitButton1_ButtonClick(sender As Object, e As EventArgs) Handles ToolStripSplitButton1.ButtonClick
        ToolStripSplitButton1.ShowDropDown()
    End Sub

    Private Sub ToolStripSplitButton2_ButtonClick(sender As Object, e As EventArgs) Handles ToolStripSplitButton2.ButtonClick
        ToolStripSplitButton2.ShowDropDown()
    End Sub

    ' 功能一：保存时整理数据
    Private Sub OrganizeDataBeforeSave()
        If dataTable Is Nothing OrElse dataTable.Rows.Count < 2 Then
            Return
        End If
        Dim restart As Boolean = True
        Dim maxIterations As Integer = 100 ' 防止无限循环
        Dim iterationCount As Integer = 0

        While restart AndAlso iterationCount < maxIterations
            restart = False
            iterationCount += 1

            For i = dataTable.Rows.Count - 1 To 1 Step -1
                Dim row = dataTable.Rows(i)
                Dim unitName = row("单元名称").ToString()
                Dim theme = row("单元主题").ToString()

                ' 跳过空单元名称的行
                If String.IsNullOrWhiteSpace(unitName) Then Continue For

                Dim foundMatch As Boolean = False

                ' 向前查找相同单元的行
                For j = i - 1 To 0 Step -1
                    Dim tmprow = dataTable.Rows(j)
                    Dim tmpUnitName = tmprow("单元名称").ToString()

                    If unitName = tmpUnitName Then
                        foundMatch = True

                        ' 修正主题
                        If theme <> tmprow("单元主题").ToString() Then
                            row("单元主题") = tmprow("单元主题").ToString()
                        End If

                        ' 如果需要移动
                        If i - j > 1 Then
                            ' 创建新行并复制数据
                            Dim newRow = dataTable.NewRow()
                            newRow.ItemArray = row.ItemArray

                            ' 删除原行
                            dataTable.Rows.Remove(row)

                            ' 插入到目标位置之后
                            dataTable.Rows.InsertAt(newRow, j + 1)

                            ' 设置重启标志
                            restart = True
                        End If

                        Exit For
                    End If
                Next

                ' 如果找到匹配，跳出内层循环
                If restart Then Exit For
            Next
        End While

    End Sub

    Private Sub UiDataGridView1_KeyDown(sender As Object, e As KeyEventArgs) Handles UiDataGridView1.KeyDown
        If e.Control AndAlso e.KeyCode = Keys.V Then
            ' 处理粘贴操作
            PasteData()
            e.SuppressKeyPress = True ' 阻止默认的粘贴行为
        End If
    End Sub
    Private Sub PasteData()
        If UiDataGridView1.CurrentCell Is Nothing Then
            Return
        End If

        isPasting = True
        Try
            Dim clipboardData = Clipboard.GetText()
            If String.IsNullOrWhiteSpace(clipboardData) Then
                Return
            End If

            ' 解析剪贴板数据（按行和列分割）
            Dim rows = clipboardData.Split({vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries)
            Dim startRow = UiDataGridView1.CurrentCell.RowIndex
            Dim startCol = UiDataGridView1.CurrentCell.ColumnIndex

            For i = 0 To rows.Length - 1
                Dim rowData = rows(i).Split(ControlChars.Tab)
                Dim rowIndex = startRow + i

                ' 检查行索引是否有效
                If rowIndex >= UiDataGridView1.RowCount Then
                    ' 添加新行
                    dataTable.Rows.Add(dataTable.NewRow())
                    UiDataGridView1.Rows.Add()
                End If

                For j = 0 To rowData.Length - 1
                    Dim colIndex = startCol + j

                    ' 检查列索引是否有效
                    If colIndex < UiDataGridView1.ColumnCount Then
                        Dim cell = UiDataGridView1.Rows(rowIndex).Cells(colIndex)
                        cell.Value = rowData(j)
                    End If
                Next
            Next
        Catch ex As Exception
            MessageBox.Show($"粘贴失败: {ex.Message}")
        Finally
            isPasting = False
        End Try
    End Sub

    Private Sub UiDataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles UiDataGridView1.CellClick
        If e.RowIndex < 1 OrElse e.ColumnIndex < 1 Then
            Return
        End If

        Dim cell = UiDataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)

        ' 如果单元格为空且不是第一行
        If String.IsNullOrWhiteSpace(cell.Value?.ToString()) Then
            Dim prevCell = UiDataGridView1.Rows(e.RowIndex - 1).Cells(e.ColumnIndex)

            ' 复制上一行相同列的值
            If prevCell.Value IsNot Nothing Then
                cell.Value = prevCell.Value
            End If
        End If
    End Sub

    Private Sub DataGridView1_MouseDown(sender As Object, e As MouseEventArgs) Handles UiDataGridView1.MouseDown
        If e.Button = MouseButtons.Left Then
            Dim hitTest = UiDataGridView1.HitTest(e.X, e.Y)
            dragRowIndex = hitTest.RowIndex
            If dragRowIndex > -1 Then
                    Dim dragSize = SystemInformation.DragSize
                    dragCursorRect = New Rectangle(New Point(e.X - dragSize.Width \ 2, e.Y - dragSize.Height \ 2), dragSize)
                Else
                    dragCursorRect = Rectangle.Empty
                End If
            End If
    End Sub

    Private Sub DataGridView1_MouseMove(sender As Object, e As MouseEventArgs) Handles UiDataGridView1.MouseMove
        If e.Button = MouseButtons.Left Then
            If dragCursorRect <> Rectangle.Empty AndAlso Not dragCursorRect.Contains(e.X, e.Y) Then
                UiDataGridView1.DoDragDrop(dragRowIndex, DragDropEffects.Move)
            End If
        End If
    End Sub

    Private Sub DataGridView1_DragOver(sender As Object, e As DragEventArgs) Handles UiDataGridView1.DragOver
        e.Effect = DragDropEffects.Move
    End Sub

    Private Sub DataGridView1_DragDrop(sender As Object, e As DragEventArgs) Handles UiDataGridView1.DragDrop
        Dim clientPoint = UiDataGridView1.PointToClient(New Point(e.X, e.Y))
        Dim hitTest = UiDataGridView1.HitTest(clientPoint.X, clientPoint.Y)

        Dim sourceRowIndex = CInt(e.Data.GetData(GetType(Integer)))
        If sourceRowIndex < 0 OrElse hitTest.RowIndex < 0 Then Return

        If hitTest.RowIndex <> sourceRowIndex Then
            ' 移动行
            Dim row = dataTable.Rows(sourceRowIndex)
            Dim newRow = dataTable.NewRow()
            newRow.ItemArray = row.ItemArray

            ' 删除原行
            dataTable.Rows.RemoveAt(sourceRowIndex)

            ' 插入到新位置
            dataTable.Rows.InsertAt(newRow, hitTest.RowIndex)

            ' 选中新位置的行
            UiDataGridView1.CurrentCell = UiDataGridView1.Rows(hitTest.RowIndex).Cells(0)
        End If
    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        ' 确认操作
        If MessageBox.Show("确定要清空所有单词吗？此操作不可撤销！",
                          "确认清空",
                          MessageBoxButtons.YesNo,
                          MessageBoxIcon.Warning) = DialogResult.No Then
            Return
        End If

        dataTable.Clear()
        UiDataGridView1.DataSource = Nothing
        ' 检查文件是否存在
        If File.Exists(当前教材Path) Then
            Try
                ' 删除文件
                File.Delete(当前教材Path)
                ShowSuccessTip("教材已成功删除！")
            Catch ex As Exception
                ShowErrorTip("删除文件时出错: " & ex.Message)
            End Try
        Else
            ShowErrorTip("文件不存在。")
        End If

    End Sub

    Private Sub 由Excel导入ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 由Excel导入ToolStripMenuItem.Click
        Try
            ' 设置编码支持中文
            'Encoding.RegisterProvider(CodePagesEncodingProvider.Instance)

            Using openFileDialog As New OpenFileDialog()
                openFileDialog.Filter = "Excel Files|*.xlsx;*.xls"
                openFileDialog.Title = "选择Excel题库文件"
                If openFileDialog.ShowDialog() = DialogResult.OK Then
                    Dim Stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read)
                    Using reader = ExcelReaderFactory.CreateReader(Stream)
                        ' 读取Excel为DataSet
                        Dim config = New ExcelDataSetConfiguration With {
                            .ConfigureDataTable = Function() New ExcelDataTableConfiguration With {
                                .UseHeaderRow = True ' 使用第一行作为列名
                            }
                        }
                        Dim dataSet = reader.AsDataSet(config)

                        ' 获取第一个工作表
                        If dataSet.Tables.Count > 0 Then
                            dataTable = dataSet.Tables(0)
                            UiDataGridView1.DataSource = dataTable
                            TextBox1.Text = Path.GetFileNameWithoutExtension(openFileDialog.SafeFileName)
                            '统计单元数量
                            GetUnitsWordsCount()
                            当前教材Path = ""
                            AddCheckboxColumn()
                        Else
                            ShowErrorTip("Excel文件中没有工作表！")
                        End If
                    End Using
                End If


            End Using
        Catch ex As Exception
            ShowErrorTip($"导入失败: {ex.Message}")
        End Try
    End Sub


    Private Sub 新建空教材ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 新建空教材ToolStripMenuItem.Click
        If 当前教材Path IsNot Nothing Then
            ' 确认新建
            If MessageBox.Show("当前已打开教材，是否需要保存后关闭当前题库？", "确认保存", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                SaveData()
            End If
        End If

        当前教材Path = ""
        If dataTable IsNot Nothing Then dataTable.Clear()
        TextBox1.Text = ""
        TextBox2.Text = ""
        Label3.Text = "单元数：0"
        Label4.Text = "单词数：0"
        AddNewRow()
        AddCheckboxColumn()
    End Sub

    Private Sub ToolStripButton5_ButtonClick(sender As Object, e As EventArgs) Handles ToolStripButton5.ButtonClick
        ToolStripButton5.ShowDropDown()
    End Sub

    Private Sub 导出Excel教材模板ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 导出Excel教材模板ToolStripMenuItem.Click

        ' 检查模版文件是否存在
        Dim ModelFile As String = Application.StartupPath & "\Data\教材模版.xlsx"

        If File.Exists(ModelFile) Then
            Try
                ' 保存JSON文件
                Using saveDialog As New SaveFileDialog
                    saveDialog.Filter = "Excel文件|*.xlsx"
                    saveDialog.DefaultExt = "*.xlsx"
                    saveDialog.FileName = "教材模版.xlsx"
                    If saveDialog.ShowDialog() = DialogResult.OK Then
                        If saveDialog.FileName = ModelFile Then
                            ShowErrorTip("不许覆盖原教材模版文件！")
                        Else
                            ' 复制文件
                            File.Copy(ModelFile, saveDialog.FileName, True) ' 第三个参数为True表示如果目标文件已存在，则覆盖它

                            ShowSuccessTip("导出模版文件成功！")
                        End If

                    End If
                End Using

            Catch ex As Exception
                ShowErrorTip("导出模版文件时出错: " & ex.Message)
            End Try
        Else
            ShowErrorTip("模板文件不存在。")
        End If



    End Sub
End Class